package com.company.stack;

import java.util.Stack;

public class BackspaceCompare {
    public boolean backspaceCompare(String S, String T) {

        if (S == null && T == null) {
            return true;
        }
        if (S == null || T == null) {
            return false;
        }

        Stack<Character> S1 = processStr(S);
        Stack<Character> S2 = processStr(T);

        if (S1.size() != S2.size()) {
            return false;
        }

        while (!S1.isEmpty()){
            Character c1 = S1.pop();
            Character c2 = S2.pop();
            if (c1 !=c2) {
                return false;
            }
        }
        return true;
    }


    private Stack<Character> processStr(String str) {
        Stack<Character> characterStack = new Stack<>();
        for (char c : str.toCharArray()) {
            switch (c) {
                case '#' -> {
                    if (!characterStack.isEmpty()) {
                        characterStack.pop();
                    }
                }
                default -> characterStack.push(c);
            }
        }
        return characterStack;
    }
}
